package com.gengzp.system.facade.impl;

import com.gengzp.common.enums.PermissionEnum;
import com.gengzp.common.exception.BusinessException;
import com.gengzp.system.facade.IPermissionFacade;
import com.gengzp.system.mapper.UserRoleRelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName PermissionFacadeImpl
 * @Description 权限模块门面层实现
 * @Author gengzp
 * @Date 2025/5/17 13:24
 */
@Service
public class PermissionFacadeImpl implements IPermissionFacade {

    @Autowired
    private UserRoleRelationMapper userRoleRelationMapper;

    @Override
    public List<Long> searchRoleIdsByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            return Collections.emptyList();
        }

        return userRoleRelationMapper.searchRoleIdsByUserId(userId);
    }

    @Override
    public Map<String, String> searchPermissionCode2NameMap() {
        return Arrays.stream(PermissionEnum.values())
                .collect(Collectors.toMap(PermissionEnum::getPermissionCode, PermissionEnum::getPermissionName));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeUserRoleRelationByRoleId(Long roleId) {
        if (Objects.isNull(roleId)) {
            throw BusinessException.get("角色id不能为空");
        }

        userRoleRelationMapper.deleteUserRoleRelationByRoleId(roleId);
    }

    @Override
    public void removeUserRoleRelationByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            throw BusinessException.get("用户id不能为空");
        }

        userRoleRelationMapper.deleteUserRoleRelationByUserId(userId);
    }

}
